package com.xlongwei.info.util;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.stream.Collectors;

import com.networknt.service.SingletonServiceFactory;
import com.networknt.utility.StringUtils;
import com.xlongwei.info.model.Info;
import com.xlongwei.info.model.User;
import com.xlongwei.info.store.Store;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Infos {

	public static Store store = SingletonServiceFactory.getBean(Store.class);

	public static String store(Info info) {
		String check = Utils.check(info);
		if (StringUtils.isNotBlank(check)) {
			log.info("check={}", check);
			return check;
		}
		Info oldInfo = Infos.info(info.getUser());
		if (oldInfo != null && oldInfo.getAcceptors().size() > 0) {
			return "已有同伴";
		}
		return store.save(info) ? null : "不能多发";
	}

	public static Collection<Info> infos() {
		Collection<Info> infos = store.infos();
		PriorityQueue<Info> queue = new PriorityQueue<>(Math.max(1, infos.size()), comparator);
		LocalDateTime now = LocalDateTime.now();
		Map<Boolean, List<Info>> map = infos.stream()
				.collect(Collectors.partitioningBy(info -> info.getEnd().isAfter(now)));
		map.get(Boolean.TRUE).forEach(info -> queue.add(info));
		map.get(Boolean.FALSE).forEach(info -> {
			log.info("delete {}", info);
			store.delete(info.getUser());
			store.backup(info);
		});
		return queue;
	}

	public static String delete(User operator, Info info) {
		if (operator.isBan()) {
			return "用户被禁";
		} else if (info == null) {
			return "没有数据";
		} else if (InfoConfig.INSTANCE.isAdmin(operator.getUser()) == false) {
			if (!operator.getUser().equals(info.getUser())) {
				return "没有权限";
			} else if (info.getAcceptors().size() > 0) {
				return "已有同伴";
			}
		}
		store.delete(info.getUser());
		return null;
	}

	public static Info info(String username) {
		return store.info(username);
	}

	public static Comparator<Info> comparator = new Comparator<Info>() {
		@Override
		public int compare(Info o1, Info o2) {
			LocalDateTime now = LocalDateTime.now();
			if (o1.getStart().isAfter(now)) {
				if (o2.getStart().isAfter(now)) {
					return o1.getStart().compareTo(o2.getStart());
				} else {
					return -1;
				}
			} else {
				if (o2.getStart().isAfter(now)) {
					return 1;
				} else {
					return o1.getEnd().compareTo(o2.getEnd());
				}
			}
		}
	};
}
